<template>
  <div id="echartBox" class="echart-box"></div>
</template>

<script>
import { init } from "echarts";

export default {
    props: {
        title: {
            type: String,
        },
        options: {
            type: Object
        }
    },
   methods: {
    drawLine() {
      //   把myChart挂载到this上去
      this.myChart = init(document.getElementById("echartBox"));
      const colors = ["#5470C6", "#91CC75", "#EE6666"];
      // 指定图表的配置项和数据
      var option = {
        color: colors,
        title: {
            top: '10',
            left: '10',
            text: this.title
        },

        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        grid: {
            top: '15%',
          right: "20%",
        },
        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        legend: {
            top: '10',
          data: ["订单数据"],
        },
        xAxis: [
          {
            type: "category",
            axisTick: {
              alignWithLabel: true,
            },
            data: this.options.xData
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "订单数据",
            min: 0,
            max: 250,
            position: "right",
            axisLine: {
              show: true,
              lineStyle: {
                color: colors[0],
              },
            },
            axisLabel: {
              formatter: "{value} 单",
            },
          },
          {
            type: "value",
            name: "总计",
            min: 0,
            max: 25,
            position: "left",
            axisLine: {
              show: true,
              lineStyle: {
                color: colors[2],
              },
            },
            axisLabel: {
              formatter: "{value}",
            },
          },
        ],
        series: [
          {
            name: "订单数据",
            type: "bar",
            data: this.options.yData
          },
        ],
      };

      this.myChart.setOption(option);
    },
    handleSize() {
      this.myChart.resize();
    },
  },
  watch: {
    options: {
      deep: true,
      handler(newValue, oldValue) {
        this.myChart.clear();
        this.drawLine()
      }
    }
  },
   mounted() {
    this.drawLine();
    // 当我们改变窗口大小时 就可以重新绘制
    window.addEventListener("resize", this.handleSize);
  },

  //   在跳转到其他路由 也就是组件销毁前的声明函数
  beforeDestroy() {
    window.removeEventListener("resize", this.handleSize);
  },
};
</script>

<style lang="less" scoped>
.echart-box {
  width: 100%;
  height: 500px;
  margin-top: 40px;
  background-color: #fff;
}
</style>